#!/usr/bin/env python
# -*- coding=utf-8 -*-

from ftplib import FTP
import sys
import threading

def ftpconnect():
    #ftp服务器的IP
    ftp_server = 'localhost'
    #ftp的用户名
    username = 'lxl'
    #用户的密码
    password = '8901'
    #创建一个ftp的实例
    ftp=FTP()
    #打开调试级别2，显示详细信息
    ftp.set_debuglevel(2)
    #连接ftp服务器，需要输入IP，端口，以及超时时间
    ftp.connect(ftp_server,21)
    #连接的用户名、密码
    ftp.login(username,password)
    return ftp
#下载
def downloadfile():
    #需要将下载文件存在的路径和文件名
    remotepath = "/home/lxl/python_ftp/ftp_commit/upload_file.txt"   #下载的文件
    #连接ftp服务器
    ftp = ftpconnect()
    #获得欢迎信息
    print ftp.getwelcome()

    bufsize = 10240
    localpath = '/home/lxl/python_ftp/ftp_commit/new_upload_file.txt'   #本地存储的位置
    with open(localpath,'wb') as fp:                                    #retrbinary是远程下载文件
        # fp = open(localpath,'wb')
        ftp.retrbinary('RETR ' + remotepath,fp.write,bufsize)
        print ("hello")
        ftp.set_debuglevel(0)
        # fp.close()
        ftp.quit()

#上传
def uploaded(filename):
    ftp = ftpconnect()
    remotepath = "/home/lxl/python_ftp/%s"%filename                   #上传的服务地址
    print ftp.getwelcome()
    bufsize = 1024
    localpath = '/home/lxl/python_ftp/ftp_commit/%s' %filename        #上传的本地文件
    with open(localpath,'rb') as fp:
        # fp = open(localpath,'rb')
        ftp.storbinary('STOR ' + remotepath,fp,bufsize)               #storbinary是向远程存储文件
        ftp.set_debuglevel(0)
        # fp.close()
        ftp.quit()

def ftp_multithreading(func,filename):
    t = threading.Thread( target = func,args=(filename,) )
    t.start()

if __name__ == "__main__":
    # ftp_multithreading(uploaded,"upload_file.txt")
    downloadfile()
